package org.changchen.fgt.utils;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;

import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;

/**   
* @ClassName:  UrlUtil   
* @Description:连接测试工具类   
* @author:     ChangChen 
* @date:       2024-01-23 11:27
* @Copyright:  2024 ChangChen. All rights reserved. 
*/
@Slf4j
public class UrlUtil {
	
	
	
	/**   
	 * @Title:      testUrl   
	 * @Description:测试URL是否可以成功连接   
	 * @param:      @param url
	 * @param:      @return      
	 * @return:     Boolean      
	 * @throws   
	 */
	public static Boolean testUrl(String url) {
		return testUrlWithTimeOut(url, 120*1000);
	}
	

	
	public static Boolean testUrlWithTimeOut(String urlString,int timeOutMillSeconds){
		
		Boolean result = false;
		
		try {
			
			HttpURLConnection httpUrlConn = (HttpURLConnection) new URL(urlString).openConnection();
	        // 设置连接主机超时（单位：毫秒）
	        httpUrlConn.setConnectTimeout(timeOutMillSeconds);
	        // 设置从主机读取数据超时（单位：毫秒）
	        httpUrlConn.setReadTimeout(timeOutMillSeconds);
	        int statusCode = httpUrlConn.getResponseCode();
	        result = (200 == statusCode);
	        // 打开流关闭
	        InputStream is2 = httpUrlConn.getInputStream();
	        is2.close();        
		} catch (Exception e) {
			// e.printStackTrace();
			result = false;
		}
		
		return result;
	}
	
	
	public static Boolean testUrlByWebClient(String url) {
		
		try {
			
			//HttpClient client = HttpClient.create().responseTimeout(Duration.ofSeconds(120)); 
			
			WebClient webClient = WebClient.builder()
			        .defaultHeader(HttpHeaders.USER_AGENT,"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)")
			        //.clientConnector(new ReactorClientHttpConnector(client))
			        .build();
			
			Mono<ClientResponse> mono = webClient.get().uri(url).exchange();
			// 获取完整的响应对象
	        ClientResponse response = mono.block();
	        HttpStatus statusCode = response.statusCode();
	        
	        // 获取响应体
//	        Mono<String> resultMono = response.bodyToMono(String.class);
//	        String body = resultMono.block();
	        
	        // 输出结果
//	        System.out.println("资源：" + url);
//	        System.out.println("statusCode：" + statusCode);
	        // System.out.println("body：" + body);
	        
	        return HttpStatus.OK.equals(statusCode);
		} catch (Exception e) {
			log.error("请求发生错误：{}", e.getMessage());
			return false;
		}
		
	}
	
	
	/**   
	 * @Title:      test   
	 * @Description:直播地址连通性测试   
	 * @param:      @param url
	 * @param:      @return      
	 * @return:     Boolean      
	 * @throws   
	 */
	public static Boolean testLiveUrl(String url){
		
		try {	
			// 忽略 SSL 认证
			SslContext sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
			HttpClient httpClient = HttpClient.create().secure(t -> t.sslContext(sslContext));	
			WebClient webClient = WebClient.builder().clientConnector(new ReactorClientHttpConnector(httpClient)).build();

			ClientResponse response = webClient.get().uri(url).exchange().block();			
			HttpStatus statusCode = response.statusCode(); // 获取响应码
			System.out.println(statusCode);
			
			return HttpStatus.OK.equals(statusCode);
	        
		} catch (Exception e) {
			log.error("{} 连通性测试发生错误 {}", url, e.getLocalizedMessage());
		}

		return false;
	}
	
	
	private UrlUtil() {}
	
	
}
